package com.jic.order.utils;

import com.google.common.io.BaseEncoding;
import org.springframework.util.Assert;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


public class AESUtils {
    private static byte[] key;

    public static byte[] getKey() {
        return key;
    }

    public static void setKey(byte[] key) {
        AESUtils.key = key;
    }

    private static String value = "F54F7C0827C97D521A7E1F47754F9CD6";


    public static String encryptWithECB(String plainText) throws Exception {
        Assert.notNull(plainText, "plainText is null");
        byte[] eBytes = encryptWithECB(plainText.getBytes("UTF-8"), key);
        return "{AES}" + BaseEncoding.base64().encode(eBytes);
    }

    public static String decryptWithECB(String encryptedText) throws Exception {
        Assert.notNull(encryptedText, "encryptedText is null");

        if (encryptedText.startsWith("{AES}") && encryptedText.length() > 5) {
            byte[] eBytes = BaseEncoding.base64().decode(encryptedText.substring(5));
            byte[] bytes = AESUtils.decryptWithECB(eBytes, key);
            return new String(bytes, "UTF-8");
        } else {
            return encryptedText;
        }

    }

    public static byte[] encryptWithECB(byte[] text, byte[] key) throws Exception {
        SecretKeySpec aesKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // default, same as "AES"
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        return cipher.doFinal(text);
    }

    public static byte[] decryptWithECB(byte[] text, byte[] key) throws Exception {
        SecretKeySpec aesKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return cipher.doFinal(text);
    }

    public static String decrp(String es){
        try {
            byte[] bytes =  decryptWithECB(BaseEncoding.base64().decode(es), BaseEncoding.base16().decode(value));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) throws Exception {
        System.out.println(decrp("yAxgn6zeSpsroeJplns966lk488r2JnLo+VIYk/GK+CQm+/gxAsOcaynMf6iC7cCSLTryjr69sb0m9HDzUWR2Q=="));
    }
}



